package xyz.lwm.lazycat.annotation;

import xyz.lwm.lazycat.beans.BeanDesign;
import xyz.lwm.lazycat.beans.Condition;
import xyz.lwm.lazycat.utility.StringUtil;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

/**
 * 条件注解，当满足条件时才加载该类
 *
 * @author lwm
 */
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.TYPE, ElementType.METHOD})
@Conditional(ConditionalOnProperty.OnPropertyCondition.class)
public @interface ConditionalOnProperty {

    /**
     * setting 属性前缀
     */
    String prefix();

    /**
     * setting 属性名
     */
    String name();

    /**
     * setting 属性值
     */
    String havingValue();

    class OnPropertyCondition implements Condition {

        @Override
        public boolean matches(Context ctx, BeanDesign<?> design) {

            ConditionalOnProperty onProperty = design.getAnnotations()
                    .getAnnotation(ConditionalOnProperty.class);
            String prefix = onProperty.prefix();
            String name = onProperty.name();
            String havingValue = onProperty.havingValue();

            if (StringUtil.isBlank(prefix) && StringUtil.isBlank(name) ||
                    StringUtil.isBlank(havingValue)) {
                return false;
            }

            String key;
            if (StringUtil.isBlank(prefix)) {
                key = name;
            } else if (StringUtil.isBlank(name)) {
                key = prefix;
            } else {
                key = prefix + "." + name;
            }

            return ctx.getSetting().get(key).let(val ->
                    !StringUtil.isBlank(val) && val.trim().equals(havingValue.trim())
            ).getOr(false);

        }
    }


}
